/**
 * 
 */
package face.unisannio;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore.Images.Media;
import android.widget.Toast;

import com.github.mhendred.face4j.DefaultFaceClient;
import com.github.mhendred.face4j.FaceClient;
import com.github.mhendred.face4j.exception.FaceClientException;
import com.github.mhendred.face4j.exception.FaceServerException;
import com.github.mhendred.face4j.model.Photo;

import face.unisannio.content.StudentDB;

/**
 * @author Fabio Melillo
 * 
 */
public class QueryFaceTask extends AsyncTask<File, Integer, Photo> {

	protected static final String API_KEY = "0889a9494b9775f3fadd8ef7179ab671";
	protected static final String API_SEC = "4f670ea4195306cbc88a940d5d1b72d2";
	protected static final String NAMESPACE = "fabio.melillo";
	private ProgressDialog dialog;
	private FaceRecognitionActivity activity;
	private FaceClient faceClient;
	private Photo photo;
	private int pixelLimit = 900;
	private String classFilter;

	public QueryFaceTask(FaceRecognitionActivity activity, String classFilter) {
		this.activity = activity;
		this.classFilter = classFilter;
	}

	protected void onPreExecute() {
		dialog = ProgressDialog.show(activity, "",
				"Sto riconoscendo i volti. Attendere prego...", true);
		dialog.setIndeterminate(true);
		dialog.setCancelable(false);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.os.AsyncTask#doInBackground(Params[])
	 */
	@Override
	protected Photo doInBackground(File... files) {
		try {
			faceClient = new DefaultFaceClient(API_KEY, API_SEC);
			File tempFile = new File(activity.getExternalFilesDir(null),
					"temp.jpg");
			FileOutputStream fos = new FileOutputStream(tempFile); // intermediate
																	// file to
																	// store
																	// compressed
																	// image
			Bitmap captureBmp = Media.getBitmap(activity.getContentResolver(),
					Uri.fromFile(files[0]));
			int largh = captureBmp.getWidth();
			int alt = captureBmp.getHeight();
			double coeff = 1;
			if (largh > pixelLimit)
				coeff = (float) pixelLimit / (float) largh;
			else if (alt > pixelLimit)
				coeff = (float) pixelLimit / (float) alt;
			if (coeff != 1) {
				Bitmap resizedBitmap = Bitmap.createScaledBitmap(captureBmp,
						(int) (captureBmp.getWidth() * coeff),
						(int) (captureBmp.getHeight() * coeff), true);
				resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);
			}

			String uids = getFilteredUids();
			photo = faceClient.recognize(tempFile, uids);
			// photo = faceClient.recognize(tempFile, "all@" + NAMESPACE);
		} catch (FaceClientException e) {
			e.printStackTrace();
		} catch (FaceServerException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return photo;
	}

	private String getFilteredUids() {
		String uids = "";
		if (classFilter != null) {
			StudentDB sdb = new StudentDB(activity);
			if (sdb.open()) {
				String params = StudentDB.STUDENT_CLASSE + "=? ";
				String[] paramsArg = { classFilter };
				String[] uidsArray = sdb.getStringArray(StudentDB.STUDENT_UID,
						params, paramsArg, null, null, null);
				int size = uidsArray.length;
				int i;
				for (i = 0; i < size - 1; i++) {
					uids += uidsArray[i] + "@" + NAMESPACE + ", ";
				}
				uids += uidsArray[i] + "@" + NAMESPACE;
			}
		} else {
			uids = "all@" + NAMESPACE;
		}

		return uids;
	}

	@Override
	protected void onPostExecute(Photo result) {
		super.onPostExecute(result);
		activity.setPhoto(result);
		activity.tagFaces();
		try {
			dialog.dismiss();
		} catch (Exception e) {
			e.printStackTrace();
			Toast toast = Toast
					.makeText(
							activity,
							"Riconoscimento completato",
							Toast.LENGTH_LONG);
			toast.show();
//			AlertDialog.Builder builder = new AlertDialog.Builder(activity);
//			builder.setMessage("Riconoscimento completato")
////			builder.setTitle("Scegli l'azione da intraprendere")
//					.setCancelable(false)
//					.setPositiveButton("Ok",
//							new DialogInterface.OnClickListener() {
//								public void onClick(DialogInterface dialog,
//										int id) {
//									// TODO
//									activity.tagFaces();
//								}
//							}).show();
//			AlertDialog alert = builder.create();
		}
	}

	public void setActivity(FaceRecognitionActivity faceRecognitionActivity) {
		activity = faceRecognitionActivity;
	}
}
